package handler

import (
	"context"
	"fmt"
	"math/rand"
	"strconv"
	"takeout/server/global"
	"takeout/server/internal/model/dao"
	"takeout/server/internal/model/service"
	"takeout/server/pkg"
	pb "takeout/server/proto"
	"time"
)

type UserServer struct {
	pb.UnimplementedUserServer
}

func (u *UserServer) SendCode(ctx context.Context, req *pb.SendCodeRequest) (resp *pb.SendCodeResponse, err error) {

	code := rand.Intn(9000) + 1000

	_, err = pkg.SendSms(req.Mobile, req.Code)
	if err != nil {
		return nil, fmt.Errorf("短信发送失败")
	}
	key := "sendCode" + req.Mobile
	sendCode := global.Rdb.Set(key, code, time.Minute*2)
	fmt.Println(sendCode)
	return &pb.SendCodeResponse{}, nil

}

func (u *UserServer) Login(ctx context.Context, req *pb.LoginRequest) (resp *pb.LoginResponse, err error) {

	var user dao.User
	if err = global.DB.Where("mobile  =  ?", req.Mobile).First(&user).Error; err != nil {
		return nil, fmt.Errorf("手机号不存在")
	}
	if user.Password != req.Password {
		return nil, fmt.Errorf("密码错误")
	}
	key := "sendCode" + req.Mobile
	info, err := global.Rdb.Get(key).Int()
	if err != nil {
		return nil, fmt.Errorf("获取短信验证码失败")
	}
	if info != int(req.Code) {
		return nil, fmt.Errorf("请重新输入短信验证码输入有误")
	}

	userinfo := "userinfo" + req.Mobile
	global.Rdb.Set(userinfo, user.ID, time.Minute*30)

	return &pb.LoginResponse{Id: int32(user.ID)}, nil

}
func (u *UserServer) Userinfo(ctx context.Context, req *pb.UserinfoRequest) (resp *pb.UserinfoResponse, err error) {

	var user dao.User
	if err = global.DB.Where("mobile = ?", req.Mobile).First(&user).Error; err != nil {
		return nil, fmt.Errorf("手机号不存在")
	}
	key := "user_unique_id" + strconv.Itoa(user.ID)
	global.Rdb.Set(key, user.Mobile, time.Minute*30)
	return &pb.UserinfoResponse{Mobile: user.Mobile}, nil

}

func (u *UserServer) SyncMerchantInfo(ctx context.Context, req *pb.SyncMerchantInfoRequest) (resp *pb.SyncMerchantInfoResponse, err error) {

	_, err = service.SyncRedis(req.Name)
	if err != nil {
		return nil, fmt.Errorf("同步失败")
	}
	return &pb.SyncMerchantInfoResponse{Message: "商家信息同步Redis成功"}, nil
}
